package com.google.coffeeshop.business;

import java.util.Date;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;

import vn.bang.utility.DateUtil;
import vn.bang.utility.JpaUtil;

import com.google.coffeeshop.dao.DAOFactory;
import com.google.coffeeshop.dao.UserDAO;
import com.google.coffeeshop.entity.UserDTO;
import com.google.coffeeshop.log.Log;

public class LoginBusiness extends AbstractBaseBusiness {
	
	static public boolean login(final String username, final String md5Password) {
		final EntityManager entityManager = createEntityManager();
		UserDTO user = null;
		try {
			JpaUtil.beginTransaction(entityManager);
				user = findByUsername(username, entityManager);
				if (null == user || !md5Password.equals(user.getPassword())) {
					return Boolean.FALSE;
				}
				updateLastTime(user, DateUtil.getNow(), entityManager);
			JpaUtil.commitEntityManager(entityManager);
			
		} catch(PersistenceException persistenceException) {
			JpaUtil.rollbackEntityManager(entityManager);
			Log.error(persistenceException);
		} finally {
			JpaUtil.closeEntityManager(entityManager);
		}
		return Boolean.TRUE;
	}
	
	static public boolean login(final String username, final char[] password) {
		final EntityManager entityManager = createEntityManager();
		UserDTO user = null;
		try {
			JpaUtil.beginTransaction(entityManager);
				user = findByUsername(username, entityManager);
				if (null == user || !encryptMD5(password).equals(user.getPassword())) {
					return Boolean.FALSE;
				}
				updateLastTime(user, DateUtil.getNow(), entityManager);
			JpaUtil.commitEntityManager(entityManager);
			
		} catch(PersistenceException persistenceException) {
			JpaUtil.rollbackEntityManager(entityManager);
			Log.error(persistenceException);
		} finally {
			JpaUtil.closeEntityManager(entityManager);
		}
		return Boolean.TRUE;
	}

	private static UserDTO updateLastTime(final UserDTO user, final Date date, final EntityManager entityManager) {
		final UserDAO userDAO = DAOFactory.createUserDAO(entityManager);
		user.setLastLoginTime(date);
		return userDAO.merge(user);
	}
	
}
